const app = getApp();
const dataNow = Date.now();
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    dataNows: dataNow,
    mock: [],
    panelIndex: 0,
    zhaosCut: "1",
    shareShow: false,
    showEarnings: false,
    page: 1,
    status: false,
    commission_name: '', // 分销订单自定义字样
    showTime: false, //搜索时间-底部弹窗
    currentShowTime: '',//显示-当前时间
    currentDate: new Date().getTime(), //当前时间
    minDate:new Date(2010, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      return type === 'year' ? `${value}年` : `${value}月`;
    },
    image_url:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "ind") {
            this.setData({
              panelIndex: chil_arr[1],
            });
          } else if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          }
        }
      }
    }
    this.getdata(this.data.panelIndex);

    this.setData({
      imgPath: app.globalData.imgPath,
      currentShowTime: this.timestampToTime(new Date())
    })
  },
  Earnings() {
    this.setData({
      showEarnings: true,
    });
  },
  goWd() {
    wx.navigateTo({
      url: "/packageC/microshop/microShop_home/microShop_home",
    });
  },
  tapCut(e) {
    let id = e.currentTarget.dataset.ind;
    const idToTitle = { 
      "1": "staffLevel", 
      "2": "merchantLevel", 
    }; 
     
    const title = idToTitle[id]; 
    if (title) { 
      this.setData({ 
        title, 
        zhaosCut: id
      }); 
      this.inData(title); 
    } 
  },
  apply(e) {
    if (!this.data.title) return
    const titleToUrl = { 
      commission: "/packageA/member/extension/ExtensionApply/ExtensionApply", 
      areaDividend: "/packageB/member/income/applyRegionalAgency/applyRegionalAgency", 
      teamDividend: "/packageA/member/extension/ExtensionApply/ExtensionApply", 
      micro: "/packageC/microshop/microShop_apply/microShop_apply", 
      staffLevel: "/packageB/member/enterprise/enterprise_apply/enterprise_apply", 
      merchantLevel: "/packageB/member/enterprise/enterprose_center_apply/enterprose_center_apply", 
      room: "/packageD/directSeeding/anchorApply/anchorApply", 
    }; 
    const url = titleToUrl[this.data.title]; 
    if (url) { 
      wx.navigateTo({ 
        url, 
      }); 
    } 
  },
  goDetail(e) {
    if (!this.data.title) return
    const titleToUrl = { 
      commission: "/mircoApp/commission/distribution/index", 
      areaDividend: "/packageB/member/income/regionalAgencyCenter/regionalAgencyCenter", 
      teamDividend: "/packageB/member/income/teamAgentCenter/teamAgentCenter", 
      staffLevel: "/packageB/member/enterprise/enterprise_index/enterprise_index", 
      merchantLevel: "/packageB/member/enterprise/enterprise_index/enterprise_index", 
      room: "/packageD/directSeeding/liveDividend/liveDividend",
      linkMove: '/packageF/chaining/index'
    }; 
     const url = titleToUrl[this.data.title]; 
    if (url) { 
      wx.navigateTo({ 
        url, 
      }); 
    } 
  },
  goTx() {
    wx.navigateTo({
      url: "/packageA/member/withdrawal/withdrawal",
    });
  },
  chooseTabData(e) {
    console.log(e);
    let ind = e.detail.index;
    let title = e.detail.title;
    this.setData({
      panelIndex: ind,
      page: 1,
      isCut: "",
    });
    const titleToTapin = { 
      [this.data.commission_title]: "commission", 
      [this.data.team_dividend_title]: "teamDividend", 
      "招商": this.data.zhaosCut == 1?'staffLevel':'merchantLevel', 
      [this.data.micro_title]: "micro", 
      [this.data.area_dividend_title]: "areaDividend", 
      [this.data.room_title]: "room", 
      [this.data.income_title]: "income",
      [this.data.link_move_title]: "linkMove", 
    }; 
    const tapin = titleToTapin[title]; 
    if (tapin) { 
      this.setData({ 
        title: typeof tapin === "function" ? tapin() : tapin, 
      }); 
    } 
    this.inData(tapin);

  },
  showTap(e) {
    this.setData({
      shareShow: true,
    });
    wx.showLoading({
      title: "海报加载中",
    });
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.ranking.api.poster.generateGoodsPoster"
    );
    app._getNetWork({
      url: urlStr,
      data: {
        getSwitch: "getSwitch",
        plugin_type: that.data.title,
        id: that.data.panelIndex,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            image_url: res.data.image_url,
          });
          wx.hideLoading();
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
          wx.hideLoading();
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  couponclose() {
    this.setData({
      shareShow: false,
      showEarnings: false,
    });
  },
  goHome() {
    wx.reLaunch({
      url: "/packageG/index/index",
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log(this.data.current_page, this.data.last_page);
    if (this.data.current_page >= this.data.last_page) {
      return;
    } else {
      let pages = this.data.page + 1;
      this.setData({
        page: pages,
      });
      this.inDataMore(this.data.title);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  onShareTimeline(){},
  getdata(key) {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.ranking.api.index.index");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        console.log(res);
        if (res.result == 1) {
          that.setData({
            commission: res.data.getSet.commission,
            merchantLevel: res.data.getSet.merchantLevel,
            micro: res.data.getSet.micro,
            staffLevel: res.data.getSet.staffLevel,
            team_dividend: res.data.getSet.team_dividend,
            area_dividend: res.data.getSet.area_dividend,
            room: res.data.getSet.room,
            getSet: res.data.getSet,
            commission_title: res.data.getSet.commission_title,
            merchantLevel_title: res.data.getSet.merchantLevel_title,
            staffLevel_title: res.data.getSet.staffLevel_title,
            micro_title: res.data.getSet.micro_title,
            team_dividend_title: res.data.getSet.team_dividend_title,
            area_dividend_title: res.data.getSet.area_dividend_title,
            room_title: res.data.getSet.room_title,
            income_title: res.data.getSet.income_title, //收入
            thumb: res.data.getSet.thumb,
            txTitle: res.data.getSet.title,
            member_name: res.data.getSet.member_name || '会员',
            commission_name: res.data.getSet.commission_order,
            link_move_title: res.data.getSet.link_move_title,
            current_page:res.data.getSwitch&&res.data.getSwitch.rankingCommission.current_page || 1,
            last_page:res.data.getSwitch&&res.data.getSwitch.rankingCommission.last_page || 1
          });
         
          const { getSet } = res.data;
          const mock = [
            getSet.commission_title,
            getSet.micro_title,
            getSet.team_dividend_title,
            getSet.area_dividend_title,
            getSet.room_title,
            (getSet.merchantLevel_title || getSet.staffLevel_title) && "招商",
            getSet.income_title,
            getSet.link_move_title
          ].filter(Boolean);

          const tapin = {
            [getSet.commission_title]: "commission",
            [getSet.team_dividend_title]: "teamDividend",
            招商: that.data.zhaosCut === 1 ? "staffLevel" : that.data.zhaosCut === 2 ? "merchantLevel" : undefined,
            [getSet.micro_title]: "micro",
            [getSet.area_dividend_title]: "areaDividend",
            [getSet.room_title]: "room",
            [getSet.income_title]: "income",
            [getSet.link_move_title]: 'linkMove'
          }[mock[key]];

          that.setData({
            mock,
            title: tapin,
          });
          that.inData(tapin);
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  inData(key) {
    wx.showLoading({
      title: "加载中",
    });
    let json = {
      getSwitch: "getSwitch",
      plugin_type: key,
    };
    if(key == 'income') { // 收入-传参
      json = {
        getSwitch: 1,
        plugin_type: key,
        create_month : this.data.currentShowTime.split('-')[0]+ this.data.currentShowTime.split('-')[1]
      }
    }
    let that = this;
    let urlStr = app.getNetAddresss("plugin.ranking.api.index.index");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        console.log(res);
        if (res.result == 1) {
          let list =  res.data.getSwitch;
          if(list&&list.countOrder){
            list.countOrder = res.data.getSwitch.countOrder&&Number(res.data.getSwitch.countOrder).toFixed(2) || 0;
          }
          if (!app._isTextEmpty(res.data.getSwitch)) {
            that.setData({
              current_page: res.data.getSwitch.rankingCommission.current_page,
              last_page: res.data.getSwitch.rankingCommission.last_page
            })
            if (res.data.getSwitch.status == "1") {
              that.setData({
                status: true,
                errText: res.data.getSwitch.text,
              });
            } else {
              that.setData({
                status: false,
              });
            }
          }

          that.setData({list});
          wx.hideLoading({
            complete: (res) => {},
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
          wx.hideLoading({
            complete: (res) => {},
          });
        }
      },
      fail: function (res) {
        console.log(res);
        wx.hideLoading({
          complete: (res) => {},
        });
      },
    });
  },
  inDataMore(key) {
    let json = {
      getSwitch: "getSwitch",
      plugin_type: key,
      page: this.data.page,
    };
    if(key == 'income') { // 收入-传参
      json = {
        getSwitch: 1,
        plugin_type: key,
        create_month : this.data.currentShowTime.split('-')[0]+ this.data.currentShowTime.split('-')[1],
        page: this.data.page,
      }
    }
    wx.showLoading({
      title: "加载中",
    });
    let that = this;
    let urlStr = app.getNetAddresss("plugin.ranking.api.index.index");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            "list.rankingCommission.data": that.data.list.rankingCommission.data.concat(
              res.data.getSwitch.rankingCommission.data
            ),
          });
          if (!app._isTextEmpty(res.data.getSwitch)) {
            that.setData({
              current_page: res.data.getSwitch.rankingCommission.current_page,
              last_page: res.data.getSwitch.rankingCommission.last_page,
            });
          }
          wx.hideLoading({
            complete: (res) => {},
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
          wx.hideLoading({
            complete: (res) => {},
          });
        }
      },
      fail: function (res) {
        console.log(res);
        wx.hideLoading({
          complete: (res) => {},
        });
      },
    });
  },
  saveImg() {
    // var times = _this.data.timeend - _this.data.timestart;
    wx.getSetting({
      success(res) {
        if (!res.authSetting["scope.writePhotosAlbum"]) {
          wx.authorize({
            scope: "scope.writePhotosAlbum",
            success() {
              console.log("授权成功");
            },
          });
        }
      },
    });
    var imgSrc = this.data.image_url;
    wx.downloadFile({
      url: imgSrc,
      success: function (res) {
        console.log(res);
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.showToast({
              title: "保存成功",
              icon: "none",
              duration: 2000,
            });
          },
          fail: function (err) {
            console.log(err);
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权");
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                    wx.showToast({
                      icon: "none",
                      title: "获取权限成功,再次长按保存图片",
                      duration: 1500,
                    });
                  } else {
                    wx.showToast({
                      icon: "none",
                      title: "获取权限失败,保存图片需要用户授权",
                      duration: 1500,
                    });
                  }
                },
              });
            }
          },
          complete(res) {
            console.log(res);
          },
        });
      },
    });
  },
  //日期转化
  timestampToTime(timestamp) {
    var date = new Date(timestamp);
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    let D = this.change(date.getDate()) + ' ';
    return Y + M ;
  },
  change(t) {
    if (t < 10) {
      return "0" + t;
    } else {
      return t;
    }
  },
  // 搜索时间
  searchTime() {
    this.setData({
      showTime: true,
    });
  },
  confirmTime(event) {
    this.setData({
      showTime: false,
      currentShowTime: this.timestampToTime(this.data.currentDate)
    });
    this.inData('income');
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  cancelTime() {
    this.setData({
      showTime: false,
    });
  }
});
